"""
下载器
"""
from functools import partial
from threading import Thread
import pygame

import requests
from PySide2.QtUiTools import QUiLoader
from PySide2.QtCore import QFile, Qt
import re

from PySide2.QtWidgets import QTableWidgetItem, QHeaderView, QAbstractItemView

from aigeiwang import Wangyiyun
from btools import FileTools as fts
from btools import Mysignals


class Downloader:
    """
    下载器类
    """

    def __init__(self):
        self.requests = requests
        ui_path = fts.getpath('downloader.ui')
        file = QFile(ui_path)
        file.open(QFile.ReadOnly)
        self.ui = QUiLoader().load(file)
        self.platform = 'wangyiyun'
        self.music_table = self.ui.music_list_tb
        self.search_type = 1
        self.headers = None
        sign_infos = [
            {'show_music_list': list}
        ]
        self.ms = Mysignals(sign_infos)
        self.ui.search_pushbutton.clicked.connect(self.search_handle)
        self.ms.show_music_list.connect(self.show_music_list)
        self.music_table.doubleClicked.connect(self.doubleclick_table_handle)
        radiobtns_platform = [el for el in self.ui.platform_groupbox.children() if
                              re.match(r'.*_music', el.objectName())]
        for radiobtn in radiobtns_platform:
            radiobtn.clicked.connect(partial(self.platform_btn_handle, radiobtn))

        radiobtns_search_type = [el for el in self.ui.search_type.children() if
                                 re.match(r'.*_search_type', el.objectName())]
        for radiobtn in radiobtns_search_type:
            radiobtn.clicked.connect(partial(self.search_type_btn_handle, radiobtn))

    def doubleclick_table_handle(self):
        table = self.music_table
        music_data = table.item(table.currentRow(), 0).data(Qt.UserRole)
        url = music_data.get('url')
        t = Thread(target=self.play_music, args=(url,))
        t.start()
        t.join()

    def play_music(self, url):
        fts.chdir(fts.getworkdir())
        fts.mkdir('mp3')
        filepath = fts.join(fts.getworkdir(), 'mp3', url.split('?')[1].split('=')[1])
        res = requests.get(url, headers=self.headers)
        with open(filepath, 'wb') as file:
            file.write(res.content)
        pygame.mixer.init()
        pygame.mixer.music.load(filepath)
        pygame.mixer.music.play()

    def platform_btn_handle(self, el):
        """
        接收单选框传过来的参数
        :param el: 单选框控件对象
        """
        self.platform = re.findall(r'(.*)_music', el.objectName())[0]

    def search_type_btn_handle(self, el):
        """
        接收单选框传过来的参数
        :param el: 单选框控件对象
        """
        self.search_type = el.accessibleName()

    def updata_music_list_ui(self, songs):
        print('更新歌曲列表')
        table = self.music_table
        count = table.rowCount()
        table.setSelectionBehavior(QAbstractItemView.SelectRows)
        header = table.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.Stretch)
        if len(songs[0]) == 2:
            table.setColumnCount(len(songs[0]))
            headertext = ['歌名']
            table.setHorizontalHeaderLabels(headertext)
            for song, index in songs:
                name = QTableWidgetItem()
                name.setText(song[0])
                name.setData(Qt.UserRole, song[2])
                table.insertRow(count + index - 1)
                table.setItem(0, index, name)
        if len(songs[0]) == 3:
            table.setColumnCount(len(songs[0]) - 1)
            headertext = ['歌名', '歌手']
            table.setHorizontalHeaderLabels(headertext)
            for song in songs:
                name = QTableWidgetItem()
                author = QTableWidgetItem()
                name.setText(song[0])
                author.setText(song[1])
                name.setData(Qt.UserRole, {'url': song[2]})
                table.insertRow(count)
                table.setItem(count, 0, name)
                table.setItem(count, 1, author)
                count += 1

    def show_music_list(self, songs):
        t = Thread(target=self.updata_music_list_ui, args=(songs,))
        t.start()

    def search_handle(self):
        """
        处理点击搜索按钮事件
        """
        kw = self.ui.kw.text()
        if (re.match(r'\d+', kw) and self.search_type == 1000) or (self.search_type == 1):
            if self.platform == 'wangyiyun':
                wyy = Wangyiyun()
                self.headers = wyy.headers
                songs = wyy.search(kw, self.search_type)
                self.ms.show_music_list.emit(songs)
            if self.platform == 'baidu':
                print('正在开发,敬请期待...')
                pass
            if self.platform == 'qq':
                print('正在开发,敬请期待...')
                pass
            if self.platform == 'xiami':
                print('正在开发,敬请期待...')
                pass
            if self.platform == 'kugou':
                print('正在开发,敬请期待...')
                pass
